#include <iostream>
using namespace std;
// 单例模式，优化扩展版

// 1.声明其构造函数为私有或保护
// 2.声明类Singleton<MyClass>为友元
// 3.从Singleton<MyClass>派生出MyClass
template <class T>
class Singleton
{
private:
    Singleton(const Singleton &) = delete;            // 禁用拷贝构造
    Singleton &operator=(const Singleton &) = delete; // 禁用拷贝赋值
protected:
    Singleton() {}
    virtual ~Singleton() {}

public:
    static T &instance()
    {
        static T theInstance;
        return theInstance;
    }
};

class MyClass : public Singleton<MyClass>
{
    int x;

protected:
    friend class Singleton<MyClass>;
    MyClass()
    {
        x = 0;
    }

public:
    void setValue(int n)
    {
        x = n;
    }
    int getValue()
    {
        return x;
    }
};

int main()
{
    MyClass &m = MyClass::instance();
    cout << m.getValue() << endl;
}
